import { ref } from "vue";
import router from "@/router";
import type { Imenu } from "types/menu";
import { CacheEnum } from "@/enum/cacheEnum";
import utils from "@/utils";
import type {
  RouteLocationNormalized,
  RouteLocationNormalizedLoaded,
} from "vue-router";

class Menu {
  public menus = ref<Imenu[]>([]);
  public history = ref<Imenu[]>([]);
  public close = ref(false);
  public route = ref(null as null | RouteLocationNormalized);

  constructor() {
    this.history.value = utils.store.get(CacheEnum.HISTORY_MENU) ?? [];
  }
  async init() {
    this.menus.value = await this.getMenuByRoute();
  }

  addHistoryMenu(route: RouteLocationNormalized) {
    if (!route.meta?.menu) return;
    this.route.value = route
    console.log(this.route.value.matched);
    const menu: Imenu = {
      ...route.meta?.menu,
      routeName: route.name as string,
    };
    const isHas = this.history.value.some((menu) => menu.routeName == route.name);
    if (!isHas) this.history.value.unshift(menu);
    if (this.history.value.length > 10) this.history.value.pop();

    utils.store.set(CacheEnum.HISTORY_MENU, this.history.value);
  }

  removeHistoryMenu(menu: Imenu) {
    const index = this.history.value.indexOf(menu);
    this.history.value.splice(index, 1);
    utils.store.set(CacheEnum.HISTORY_MENU, this.history.value);
  }

  toggleParentMenu(menu: Imenu) {
    this.menus.value.forEach((m) => {
      if (m == menu) m.isClick = !m.isClick;
      else m.isClick = false;
    });
  }
  toggleState() {
    this.close.value = !this.close.value;
  }

  setCurrentMenu(Route: RouteLocationNormalizedLoaded) {
    this.menus.value.forEach((m) => {
      m.isClick = false;
      m.children?.forEach((c) => {
        c.isClick = false;
        if (c.routeName == Route.name) {
          m.isClick = true;
          c.isClick = true;
        }
      });
    });
  }
  async getMenuByRoute() {
    await router.isReady();
    return router
      .getRoutes()
      .filter((route) => route.children.length && route.meta.menu)
      .map((route) => {
        let menu: Imenu = { ...route.meta?.menu };
        menu.children = route.children
          .filter((route) => route.meta?.menu)
          .map((route) => {
            return { ...route.meta?.menu, routeName: route.name };
          }) as Imenu[];
        return menu;
      })
      .filter((menu) => menu.children?.length);
  }
}
export default new Menu();
